<template>
  <div class="users">
    <breadcrumb :first="'用户管理'"></breadcrumb>
    <el-card>
      <el-input
        v-model="params.query"
        placeholder="请输入内容"
        clearable
        @clear="getuser"
      ></el-input>
      <el-button type="primary" @click="getuser">搜索</el-button>
      <el-button type="primary" @click="dialogVisible = true">添加</el-button>

      <!-- 表格 -->
      <el-table :data="userdata.users" border style="width: 100%">
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 作用域插槽通过slot-scope="scope"接受数据-->
          <template slot-scope="scope">
            <!-- 通过scope.row拿到该行所有数据 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="statechange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              @click="openedit(scope.row)"
              type="primary"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              @click="deluser(scope.row)"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
            <el-button
              @click="opengiveRole(scope.row)"
              type="warning"
              icon="el-icon-s-tools"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[2, 3, 4, 5]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userdata.total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog
      :title="isflag ? '添加用户' : '修改用户信息'"
      :visible.sync="dialogVisible"
    >
      <el-form ref="adddata" :model="adddata" label-width="80px" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adddata.username" :disabled="!isflag"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isflag">
          <el-input v-model="adddata.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="adddata.email"></el-input>
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="adddata.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="(dialogVisible = false), (adddata = {})"
          >取 消</el-button
        >
        <el-button type="primary" @click="checkflag">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色分配 -->
    <el-dialog
      title="分配角色"
      :visible.sync="opengive"
      @close="checkedrole = ''"
    >
      <p>当前的用户:{{nowrolemsg.username}}</p>
      <p>当前的角色:{{nowrolemsg.role_name}}</p>
      <p>
        分配新角色
        <el-select v-model="checkedrole" placeholder="请选择">
          <el-option
            v-for="item in giverolelist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="opengive = false">取 消</el-button>
        <el-button type="primary" @click="putgiverole"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  users,
  addusers,
  changestate,
  delusers,
  editUserMsg,
  getroleList,
  giveUserRole
} from "@/api/index";
import breadcrumb from "@/components/breadcrumb.vue";
export default {
  data() {
    return {
      params: {
        query: "",
        pagenum: 1,
        pagesize: 4,
      },
      //用户列表数据
      userdata: "",
      //弹框状态
      dialogVisible: false,
      //添加修改弹框状态
      isflag: true,
      // 添加用户数据
      adddata: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      opengive: false,
      giverolelist: {},
      checkedrole: '',
      nowrolemsg: {}
    };
  },
  components: {
    breadcrumb,
  },
  created() {
    this.getuser();
  },
  methods: {
    //分页器两个操作函数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pagesize = val;
      this.getuser();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.pagenum = val;
      this.getuser();
    },
    //获取用户列表
    getuser() {
      users(this.params).then((res) => {
        this.userdata = res.data.data;
      });
    },
    //根据isflag实现添加或修改功能
    checkflag() {
      if (this.isflag) {
        this.addUser();
      } else {
        this.edituser();
      }
    },
    // 添加用户
    addUser() {
      //添加预校验
      this.$refs.adddata.validate((valid) => {
        if (!valid) return this.$message.error("信息填写不规范");
        addusers(this.adddata).then((res) => {
          if (res.data.meta.status !== 201)
            return this.$message.error(res.data.meta.msg);
          this.$message({
            message: "添加成功",
            type: "success",
          });
        });
        this.dialogVisible = false;
        this.adddata = {};
        this.getuser();
      });
    },
    //删除用户
    deluser(data) {
      console.log(data);
      delusers(data).then((res) => {
        this.getuser();
        if (res.data.meta.status === 200)
          return this.$message({
            message: "删除成功",
            type: "success",
          });
      });
    },
    //打开修改用户对话框
    openedit(rowdata) {
      this.isflag = false;
      this.dialogVisible = true;
      this.adddata = rowdata;
    },
    //修改用户信息
    edituser() {
      //获取需要传的数据
      let editmsg = {
        id: this.adddata.id,
        mobile: this.adddata.mobile,
        email: this.adddata.email,
      };
      editUserMsg(editmsg).then((res) => {
        this.dialogVisible = false;
        if (res.data.meta.status !== 200)
          return this.$message.error(res.data.meta.msg);
        this.$message({
          message: "用户信息修改成功",
          type: "success",
        });
      });
    },
    //状态改变
    statechange(state) {
      changestate(state).then((res) => {
        if (res.data.meta.status === 200)
          return this.$message({
            message: "状态修改成功",
            type: "success",
          });
        this.$message.error("状态修改失败");
      });
    },
    opengiveRole(data) {
      this.nowrolemsg = data
      //获取角色列表
      getroleList().then( res=>{
        this.giverolelist = res.data.data
        console.log(this.giverolelist);
      })
      this.opengive = true
    },
    putgiverole(){
      giveUserRole(this.nowrolemsg.id,this.checkedrole).then( res=>{
        if(res.data.meta.status !== 200){
          return this.$message.error(res.data.meta.msg)
        }
        this.$message({
          message: '分配成功',
          type: 'success'
        })
        this.getuser();
      })
      this.opengive = false
    }
  },
};
</script>

<style lang="less" scoped>
.users {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 10px;
  background-color: #fafafa;
}

.el-input {
  width: 300px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-table {
  margin-bottom: 10px;
}
</style>
